/// <reference path="sage.util.js" />
/// <reference path="sage.input.__.base.js" />

var OrientationInput = BaseInputHandler.extend({
    initialize: function initialize() {
        BaseInputHandler.initialize.call(this, []);
        this.lastAlpha = 0;
        this.lastBeta = 0;
        this.lastGamma = 0;
        this.lastAbsolute = 0;
        this.eventName = "deviceorientation";
        this.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
        this.firefox = /firefox/.test(navigator.userAgent.toLowerCase());

        var self = this;
        this.handler = function (event) {
            var context = {
                prevent: false,
                alpha: event.alpha,
                beta: event.beta,
                gamma: event.gamma,
                absolute: event.absolute
            };

            self.sendOrientation(context);
        };
    },
    isAvailable: function isAvailable() {
        return (window.DeviceOrientationEvent);
    },
    sendOrientation: function sendOrientation(context) {
        /*this.lastAlpha = context.alpha;
        this.lastBeta = context.beta;
        this.lastGamma = context.gamma;
        this.lastAbsolute = context.absolute;
        this.readingCount++;
        this.lastWasError = false;
        for (subId in this.subscribers) {
            this.subscribers[subId].fireEvent("orientation", context);
        }*/
        if (this.lastAbsolute != context.absolute || this.lastAlpha != context.alpha ||
			this.lastBeta != context.beta || this.lastGamma != context.gamma) {

            if (null == context.alpha && null == context.beta &&
                null == context.gamma && null == context.absolute) {
                // empty readings shouldn't come back to the application
            }
            else {
                this.lastAlpha = context.alpha;
                this.lastBeta = context.beta;
                this.lastGamma = context.gamma;
                this.lastAbsolute = context.absolute;

                if (this.firefox) {
                    var a = Math.abs(360.0-context.alpha);
                    if (a > 360) a = a - 360.0;
                    context.alpha = a;
                }

                this.readingCount++;
                this.lastWasError = false;
                for (subId in this.subscribers) {
                    this.subscribers[subId].fireEvent("orientation", context);
                }
            }
        }
    },
    setup: function setup() {
        if (!this.enabled) {
            this.enabled = true;
            var self = this;
            window.addEventListener(this.eventName, this.handler, false);
        }
    },
    teardown: function teardown() {
        if (this.enabled) {
            this.enabled = false;
            clearTimeout(this.timerHandle);
            window.removeEventListener(this.eventName, this.handler, false);
        }
    }
});
